//
//  SQLiteManager.swift
//  WKweiBo
//
//  Created by 阿拉斯加的狗 on 15/12/22.
//  Copyright © 2015年 阿拉斯加的🐶. All rights reserved.
//

import Foundation


//数据库名称
private let dbName = "readme.db"

class SQLiteManager {

    //创建单例
    static let sharedManager = SQLiteManager()
    
    //创建全局队列
    let queue: FMDatabaseQueue
    
    private init() {
    
        //获取路径
        var path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last!
        
        path = (path as NSString).stringByAppendingPathComponent(dbName)
        
        print("数据库路径 " + path)
        
        //打开数据库
        queue = FMDatabaseQueue(path: path)
        
        //创建数据表
        createTable()
    }

/// 执行SQL 返回字典数据
    func execRecordSet(sql: String) -> [[String: AnyObject]] {
    
        //定义数组
        var result = [[String: AnyObject]]()
        
        //同步执行获取数据
        SQLiteManager.sharedManager.queue.inDatabase { (db) -> Void in
            
            guard let rs = db.executeQuery(sql) else {
            
                print("没有结果")
                return
            }
            
            while rs.next() {
            
                //1.获取列数
                let colCount = rs.columnCount()
                
                //创建字典
                var dict = [String: AnyObject]()
                
                //遍历每一项
                for col in 0..<colCount {
                
                    let name = rs.columnNameForIndex(col)
                    
                    let obj = rs.objectForColumnIndex(col)
                    
                    dict[name] = obj
                    
                
                }
            
                //添加到数组中
                result.append(dict)
                
            }
            
        }

        return result
    
    }
    
    
    
/// 创建表
    private func createTable() {
    
        //准备SQL
        let path = NSBundle.mainBundle().pathForResource("db.sql", ofType: nil)!
        
        let sql = try! String(contentsOfFile: path)
        
        //执行sql
        queue.inDatabase { (db) -> Void in
            
            //创建数据表
            if db.executeStatements(sql) {
            
                print("创表成功")
            
            }else {
            
                print("创表失败")
            }
            
        }
    
    
    }


}